<template>
  <div class="signUp">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      :max-badge="{ num: 100, str: '99+' }"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page signUp-list">
      <DataDisplay
        :data-list="statisticsList"
        class="mb16 mobile-data statistics-box"
      />
      <div v-if="!showMobilePage" class="filter">
        <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" is-show-config show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div v-if="!showMixedChecked" class="current-user-action-box">
          <el-checkbox v-model="isMyPending" @change="queryClick">待我处理</el-checkbox>
          <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
          <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
        </div>
        <el-dropdown v-else :hide-on-click="false" trigger="click">
          <el-button class="el-dropdown-link search-btn-style more-btn">快捷筛选<i class="el-icon-caret-bottom"/></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-checkbox v-model="isMyPending" @change="queryClick">待我处理</el-checkbox>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <createBtn v-if="hasRouteAuth('signUp:signUp:creat')" style="margin-right: 10px;" @click.native="toCreate"/>
        <MoreOpeator
          ref="moreOpeatorRef"
          :list="[
            { label: '批量抄送', handelClick: handleSendMsg },
            { label: '复制链接', handelClick: batchCopyLink },
            { label: '导出签约信息', exportApi: `admin/signUp/export`, type: 'export', auth: hasRouteAuth('crm:signUp:export'),
              exportName: '签约信息', isBeforeExport: true, beforeExport: exportSignUpInfo, refName: 'signExportRef' }
          ]"
        />
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px;">
          <u-table
            v-if="list.items.length"
            ref="tableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="49"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
              <template slot-scope="scope" slot="header">
                <div class="diyHeader">{{ scope.column.label }}</div>
              </template>
              <template slot-scope="scope">
                <processSn :is-expedited="scope.row.isExpedited">
                  <div v-if="scope.row.signUpNum" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                    <ToolTip :content="handleSnNumber(scope.row.signUpNum)" is-can-click @handelClick="toDetail(scope.row)" />
                  </div>
                  <div v-else>--</div>
                </processSn>
              </template>
            </u-table-column>
            <u-table-column align="left" label="供应商名称" min-width="130">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.supplier" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号名称" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.accountNames" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="下单平台" min-width="200">
              <template slot-scope="scope">
                <div class="flex-center">
                  <PlatformIcon :data="scope.row.platform" />
                  {{ scope.row.platform || '--' }}
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号ID" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.accountIds" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="签单签约经纪" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.agentName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="标签" min-width="200">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.tag && scope.row.tag.length" :open-delay="800" placement="top" effect="dark">
                  <div slot="content" style="max-width:300px">{{ handleStr(scope.row.tag) }}</div>
                  <div class="tag-wrap">
                    <span v-for="(t,index) in handleTags(scope.row.tag)" :key="index" :style="t.color ? `color:${t.color};background:${changeColorAlphaVal(t.color, 0.14)}` : ''" class="tag">
                      {{ t }}
                    </span>
                    <div v-if="scope.row.tag.length > 3">...</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="签约有效期" min-width="160">
              <template slot-scope="scope">
                <ToolTip :content="formatSignDate(scope.row)" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <StatusText
                  v-if="scope.row.status || scope.row.status===0"
                  :color="['#FFBC3D','#FD8546', '#FF4E5F', '#999', '#31CC9C','#406EFF'][scope.row.status]"
                  :text="scope.row.status | signUpStatus"
                />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前节点">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.currentNode" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前处理人" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.proposer" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.departmentName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="签约合同" min-width="180">
              <template slot-scope="scope">
                <div v-if="!scope.row.contractList || !scope.row.contractList.length">--</div>
                <el-tooltip v-else placement="top">
                  <div slot="content">
                    <template v-for="item in scope.row.contractList">
                      <div :key="item.id" style="color: #406eff; margin-bottom: 4px; cursor: pointer" @click="goContractDetail(item)">{{ item.contractNum || '合同编号未生成' }}</div>
                    </template>
                  </div>
                  <div style="color: #406eff;cursor: pointer" @click="goContractDetail(scope.row.contractList[0])">{{ scope.row.contractList[0].contractNum || '合同编号未生成' }}</div>
                </el-tooltip>
              </template>
            </u-table-column>
            <u-table-column align="left" label="签约状态" min-width="150">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.signStatus" :odpen-delay="800" class="sign-status-tooltip" placement="top">
                  <div slot="content" class="tooltip-content">
                    <template v-for="(item, index) in (scope.row.signStatusMapAccounts || [])">
                      <div :key="index" class="account-item-tip"> {{ `${item.accountName || '--'}(${item.status || '--'})` }} <br></div>
                    </template>
                  </div>
                  <div>
                    <StatusText
                      :color="getSignUpColor(scope.row.signStatus)"
                      :text="scope.row.signStatus"
                    />
                  </div>
                </el-tooltip>
                <div v-else>--</div>
                <!-- <div class="status-wrap">
                  <div v-if="getStatusMap(scope.row.signDetailStatus)" class="flex-center">
                    <div :style="{background: getStatusMap(scope.row.signDetailStatus).bg}" class="status-text">{{ getStatusMap(scope.row.signDetailStatus).status }}</div>
                    <span v-if="getStatusMap(scope.row.signDetailStatus).remark" class="f12 g3 ml5">{{ getStatusMap(scope.row.signDetailStatus).remark }}</span>
                  </div>
                  <span v-else>--</span>
                </div> -->
              </template>
            </u-table-column>
            <u-table-column align="left" label="到期时长" width="150" prop="expiredDuration" sortable="custom">
              <template slot-scope="scope">
                <div v-if="scope.row.signDetailStatus === SIGN_DETAIL_STATUS.WAIT_SIGN">无合同</div>
                <div v-else-if="scope.row.signDetailStatus === SIGN_DETAIL_STATUS.AUTO_RENEWAL">无新合同</div>
                <div v-else-if="scope.row.isExpired" style="color: #FF4E5F">已到期</div>
                <div v-else-if="scope.row.expiredDuration || scope.row.expiredDuration === 0">
                  距离到期日：<span :style="expiredTypeClass(scope.row.expiredDuration)">
                  {{ scope.row.expiredDuration !== 9999 ? scope.row.expiredDuration : '--' }}</span> 天</div>
                <span v-else>距离到期日：-- 天</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人">
              <template slot-scope="scope">
                <CheckUserInfo :user-id="scope.row.creatorId" :label="scope.row.createUser" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160" prop="createTime" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm:ss')" />
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" :fixed="operateFix" align="left" label="操作">
              <template slot-scope="scope">
                <div class="operate">
                  <div v-if="scope.row.status !== 0 && !showMobilePage" class="button-text br bold" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {
                        label: '查看',
                        handelClick: () => {toDetail(scope.row)},
                        auth: scope.row.status !== 0 && showMobilePage
                      },{
                        label: '复制',
                        handelClick: () => {handlerCreateNew(scope.row)},
                        disabled: scope.row.status === 0 || !hasRouteAuth('signUp:signUp:creat')
                      },{
                        label: '编辑',
                        handelClick: () => {toEdit(scope.row)},
                        disabled: setEditDisable(scope.row)
                      },{
                        label: '删除',
                        handelClick: () => {toDelete(scope.row)},
                        disabled: setDelDisable(scope.row)
                      },{
                        label: '同步资源',
                        disabled: handleSyncBtnDisable(scope.row),
                        handelClick: () => {handleSync(scope.row)}
                      }
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" class="button-text bold">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" slot="empty" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              ref="moreOpeatorRef"
              :list="[
                { label: '批量抄送', handelClick: handleSendMsg },
                { label: '复制链接', handelClick: batchCopyLink },
                { label: '导出签约信息', exportApi: `admin/signUp/export`, auth: hasRouteAuth('crm:signUp:export'),
                  type: 'export', exportName: '签约信息', isBeforeExport: true, beforeExport: exportSignUpInfo, refName: 'signExportRef' }
              ]"
              show-mobile-icon
            />
            <createBtn
              v-if="hasRouteAuth('signUp:signUp:creat')"
              mobile-table
              @click.native="toCreate"/>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
      <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
      <AccountSync ref="accountSyncRef" />
    </div>
  </div>
</template>
<script>
import axios from 'axios';// 取消未完成请求
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
// 组件
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import AccountSync from './components/accountSync';
import PlatformIcon from '@/components/Common/platformIcon';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
// fitter
import { energyStatus as signUpStatus, expeditedOptions, getSignUpColor, getStatusMap } from '@/filters/status';
// api
import { tabList, signUpList, deleteSignUp, getSignUpCount } from '@/api/signUp';
import { platformList } from '@/api/select';
import { getDepartmentAll, getTagAll } from '@/api/config';
import { format } from '@/filters/date';
import ElMessage, { showModal } from '@/utils/message';
import { PROCESS_TYPE } from '@/utils/const/process';
import { SIGN_DETAIL_STATUS } from '@/utils/const/resouce';
import { commonOptions } from '@/utils/tools';
import { TAG_MODULES } from '@/utils/const';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { encryption, getCurrentZeroTime } from '@/utils';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import tableSelections from '@/mixins/tableSelections';
import { expiredTypeClass } from './components/status';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';
import icon_54 from '@/assets/dataDisplay/icon_54.png';
import icon_55 from '@/assets/dataDisplay/icon_55.png';
import icon_56 from '@/assets/dataDisplay/icon_56.png';
import icon_57 from '@/assets/dataDisplay/icon_57.png';
import icon_58 from '@/assets/dataDisplay/icon_58.png';

export default {
  filters: { signUpStatus },
  components: {
    ListTab,
    EmptyPlaceholder,
    createBtn,
    MoreOpeator,
    AccountSync,
    DiversAuditorDialog,
    PlatformIcon,
    DataDisplay
  },
  mixins: [TableAdaptive, mobileTable, filterObjStoreMixin, tableSelections, copyLink, schedule],
  data() {
    return {
      SIGN_DETAIL_STATUS,
      tabs: [],
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      TAG_MODULES,
      tabStatus: -1,
      page: 1,
      perPage: 20,
      paramsObj: {},
      listLoading: false,
      sortName: '',
      sortType: '',
      deptTreeList: [],
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      cancelToken: null,
      orderPlatformOption: [],
      statisticsList: [],
      showMixedChecked: false,
      tagTreeList: [],
      isShowMe: false,
      isMyApproval: false,
      isMyPending: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    accountSignStatusOptions() {
      return [
        { value: 0, label: '未签约' },
        { value: 1, label: '已签约（待签合同）' },
        { value: 2, label: '已签约（已签合同）' },
        { value: 3, label: '已解约（协商解约）' },
        { value: 4, label: '已解约（到期解约）' },
        { value: 5, label: '已签约（已续约）' },
        { value: 6, label: '已签约（自动续约）' }
      ];
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'signUpNum', name: '审批单号', labelWidth: '100px', type: 'input' },
        { keyword: 'supplier', name: '供应商名称', labelWidth: '100px', type: 'input' },
        { keyword: 'accountName', name: '账号名称', labelWidth: '100px', type: 'input' },
        { keyword: 'accountId', name: '账号ID', labelWidth: '100px', type: 'input' },
        { keyword: 'contractCode', name: '签约合同编号', labelWidth: '100px', type: 'input' },
        { keyword: 'agentName', name: '签单签约经纪', labelWidth: '100px', type: 'input' },
        { keyword: 'createUser', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'currentNode', name: '当前节点', labelWidth: '100px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '100px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '100px' },
        // 下拉
        { keyword: 'status', name: '状态', type: 'select', options: commonOptions },
        { keyword: 'signDetailStatus', name: '签约状态', type: 'mulSelect', options: this.accountSignStatusOptions },
        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'platformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
        { keyword: 'tag', name: '标签', valueName: 'name', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        // 日期
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'signStartDate', name: '签约起始日期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'signEndDate', name: '签约结束日期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    rangeKeyArr() {
      return [
        { attr: 'signStartDate', start: 'signStartDateStart', end: 'signStartDateEnd', type: 'time', dayEnd: true },
        { attr: 'signEndDate', start: 'signEndDateStart', end: 'signEndDateEnd', type: 'time', dayEnd: true },
        { attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time' }
      ];
    },
    arrayKeyArr() {
      return ['signDetailStatus', 'tag'];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 256 : 272;
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    this.queryDeptTreeList();
    this.platformList();
    this.queryTagTreeList();
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'signUpCreate' || from.name === 'signUpEdit' || from.name === 'signUpDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.fetchData();
    } else {
      const { accountId, platformId } = this.$route.query;
      if (accountId && (platformId || platformId === 0)) {
        this.$set(this.paramsObj, 'accountId', accountId);
        this.$set(this.paramsObj, 'platformId', Number(platformId));
      }
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    }
  },
  mounted() {
    this.setMixedCheckedStatus();
    window.addEventListener('resize', this.setMixedCheckedStatus);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setMixedCheckedStatus);
  },
  methods: {
    hasRouteAuth,
    format,
    expiredTypeClass,
    getStatusMap,
    getSignUpColor,
    setMixedCheckedStatus() {
      this.$nextTick(() => {
        const mainVisibleDom = document.querySelector('.signUp');
        this.showMixedChecked = !!(mainVisibleDom && mainVisibleDom.offsetWidth < 1250);
      });
    },
    getDetailLink(item) {
      if (!item.status) return null;
      return `${location.origin}/#/supplierPage/signUpDetail?signUpId=${item.id}&processId=${item.processId}`;
    },
    handleSyncBtnDisable(row) {
      return row.signStatusMapAccounts ? row.signStatusMapAccounts.every(it => it.contractEndTime && it.contractEndTime < getCurrentZeroTime()) : false;
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.SIGN_UP };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    getTabs() {
      const params = this.formatParams();
      delete params.tabStatus;
      tabList(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.tabs = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    handleTags(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.slice(0, 3);
    },
    handleStr(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.join(',');
    },
    formatSignDate(row) {
      if (row.signStartDate || row.signEndDate) {
        return this.format(row.signStartDate, 'YYYY/MM/DD') + '-' + this.format(row.signEndDate, 'YYYY/MM/DD');
      } else {
        return '--';
      }
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    // 获取统计数据
    async getCostData(paramsObj = '') {
      try {
        const params = this.formatParams();
        const { page, perPage } = params;
        if (page) delete params.page;
        if (perPage) delete params.perPage;
        const res = await getSignUpCount(params);
        const { code, data = {}} = res;
        if (code === 200) {
          const { lastWeekSigned, thisWeekSigned, thisMonthSigned, thisQuarterSigned, thisYearSigned } = data;
          this.statisticsList = [
            { data: lastWeekSigned, label: '上周签约数', tooltip: '上周一～上周日签约完成的账号数', icon: icon_54, isMoney: false, width: '20%' },
            { data: thisWeekSigned, label: '本周签约数', tooltip: '本周一～周日签约完成的账号数', icon: icon_55, isMoney: false, width: '20%' },
            { data: thisMonthSigned, label: '本月签约数', tooltip: '当前月份内签约完成的账号数', icon: icon_56, isMoney: false, width: '20%' },
            { data: thisQuarterSigned, label: '本季度签约数', tooltip: '本季度内签约完成的账号数', icon: icon_57, isMoney: false, width: '20%' },
            { data: thisYearSigned, label: '本年签约数', tooltip: '本年内签约完成的账号数', icon: icon_58, isMoney: false, width: '20%' }
          ];
        }
      } catch (error) {
        console.log(error);
        this.statisticsList = [
          { data: 0, label: '上周签约数', tooltip: '上周一～上周日签约完成的账号数', icon: icon_54, isMoney: false, width: '20%' },
          { data: 0, label: '本周签约数', tooltip: '本周一～周日签约完成的账号数', icon: icon_55, isMoney: false, width: '20%' },
          { data: 0, label: '本月签约数', tooltip: '当前月份内签约完成的账号数', icon: icon_56, isMoney: false, width: '20%' },
          { data: 0, label: '本季度签约数', tooltip: '本季度内签约完成的账号数', icon: icon_57, isMoney: false, width: '20%' },
          { data: 0, label: '本年签约数', tooltip: '本年内签约完成的账号数', icon: icon_58, isMoney: false, width: '20%' }
        ];
      }
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.getTabs();
      this.getCostData();
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      signUpList(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        this.list.isInit = false;
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    formatParams() {
      const params = _.cloneDeep(this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.tabStatus = this.tabStatus;
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      return params;
    },
    setEditDisable(data) {
      return !(data.status === 0 && data.creatorId === this.userInfo.id);
    },
    setDelDisable(data) {
      const statusArr = [0, 2, 3, 5];// 草稿、已撤销、未过审、待提交
      return !(statusArr.includes(data.status) && (data.creatorId === this.userInfo.id || this.hasRouteAuth('signUp:signUp:delete')));// 除审批中和已完成状态且为创建人或者有删除权限
    },
    toCreate() {
      this.$router.push({
        name: 'signUpCreate'
      });
    },
    toEdit(row) {
      this.$router.push({
        name: 'signUpEdit',
        params: {
          id: row.id
        }
      });
    },
    toDetail(row) {
      this.filterObjStore(PROCESS_TYPE.SIGNUP);
      this.$router.push({
        name: 'signUpDetail',
        query: {
          signUpId: row.id,
          processId: row.processId,
          fromList: 1
        }
      });
    },
    toDelete(row) {
      showModal('是否确定删除?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        deleteSignUp(row.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.resetItemSelected(row.id);
          this.fetchData();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    handleSync(rowData) {
      if (!rowData || !rowData.signStatusMapAccounts || !rowData.signStatusMapAccounts.length) {
        this.$message.warning('该审批不存在可同步的账号');
        return;
      }
      const list = rowData.signStatusMapAccounts.map(item => {
        item.isExpired = item.contractEndTime ? item.contractEndTime < new Date().getTime() : false;
        const hasPlatformName = !!item.platformName;
        item.label = hasPlatformName ? `${item.accountName}(${item.platformName})` : item.accountName;
        return item;
      });
      this.$refs['accountSyncRef'].init(rowData.id, list);
    },
    goContractDetail(row) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(row.contractId) },
        query: {
          processId: encryption(row.processId),
          fromList: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    toDetailOnly() {
      const params = {
        iconClass: 'del-icon'
      };
      deleteSignUp(params).then((res) => {
        if (res.code === 200) {
          this.resetItemSelected(res.data.id);
        } else {
          this.fetchData();
        }
      }).catch(err => {
        console.log(err);
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handlerCreateNew(row) { // 再次发起（复制）
      const routeUrl = this.$router.resolve({
        name: 'signUpEdit',
        params: {
          id: row.id
        },
        query: {
          reapplyId: row.processId,
          createNew: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    exportSignUpInfo() {
      if (!this.multipleSelectionAll || this.multipleSelectionAll.length === 0) {
        ElMessage.warning('请勾选需要导出的内容!');
        return;
      }
      // const params = this.formatParams();
      const params = {};
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'signExportRef');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.signUp{
  .signUp-list{
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 24px 55px 24px;
    .statistics-box {
      &::v-deep {
        .data-item {
          padding-left: 10px;
          margin-right: 0;
        }
        .data-item:first-child {
          padding-left: 0;
        }
        .data-item:nth-of-type(4n) {
          border-right: 1px solid #DDE1EA;
        }
      }
    }
  }
  .operate{
    @include flexStyle($align:center);
  }
  .filter {
    @include flexStyle($align:center);
    margin-bottom: 16px;
    position:relative;
    margin-bottom:16px;
    .create-btn{
      height: 32px;
      font-size: 14px;
      padding: 0 15px;
    }
    .current-user-action-box {
      position: absolute;
      left: 509px;
      top: 6px;
      display:flex;
      align-items:center;
      ::v-deep {
        .el-checkbox {
          margin-right: 24px;
        }
      }
    }
  }
}
.sign-status-tooltip {
  display: inline-block;
  max-width: 100%;
  line-height: 1;
  vertical-align: middle;
  .tooltip-content {
    max-height: 200px;
    @include scrollBar($width: 6px);
  }
}
.account-item-tip {
  line-height: 1.4;
  font-size: 14px;
  text-align: center;
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
}
.more-btn{
  width: 96px;
  height: 32px;
  padding: 0;
  font-size: 14px;
  margin-right: 10px;
}
.status-wrap {
  display: flex;
  align-items: center;
  .status-text {
    width: 48px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    border-radius: 10px;
    font-size: 12px;
  }
}
.tag-wrap{
  display: flex;
  align-items: center;
  .tag{
    display: inline-block;
    max-width: 60px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color:#406EFF;
    height: 20px;
    line-height: 20px;
    font-size: 12px;
    padding: 0px 8px;
    background: #eff4ff;
    border-radius: 4px;
    margin-right: 4px;
  }
}
</style>
